<?php
namespace inkstones\session;
use SessionHandlerInterface;
use inkstones\config\Config;
use Exception;

class RedisSession implements SessionHandlerInterface{
	protected $handler='';
	
	public function __construct(){
		$this->config=Config::get('session.redis');
	}
	
	public function close( ){
		$this->gc(ini_get('session.gc_maxlifetime'));
		$this->handler->close();
		$this->handler='';
		
		return true;
	}
	
    public function destroy ($session_id )
	{
		return $this->handler->delete($this->config['session_name'].$session_id);
	}
	
    public function gc ($maxlifetime )
	{
		return true;
	}
	
    public function open ($save_path , $name )
	{
		if(!extension_loaded('redis')){
			throw new Exception('redis extension not load');
		}
		
		
		$this->handler=new Redis();
		$connect=$this->config['pconnect']?'pconnect':'connect';
		
		$this->handler->$connect($this->config['host'],$this->config['port'],$this->config['timeout']);
		
		$this->handler->auth($this->config['pwd']);
		$this->handler->select($this->config['dbname']);
		
		return true;
	}
	
    public function read ($session_id )
	{
		return (string) $this->handler->get($this->config['session_name'].$session_id);
	}
	
    public function write ($session_id , $session_data )
	{
		return $this->config['expire']>0?$this->handler->setex($this->config['session_name'].$session_id,$this->config['expire'],$session_data):$this->handler->set($this->config['session_name'].$session_id,$session_data);
	}
	
}















?>